package com.example.qx.faxiana;

import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;

import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;

import com.example.qx.R;
import com.example.qx.database.data;
import com.example.qx.databinding.ItemqxqBinding;
import com.example.qx.lei.cos;
import com.example.qx.lei.itemqxq;
import com.example.qx.lei.leilianxr;
import com.example.qx.lei.tianjianqxq;
import com.example.qx.lei.zhangmi;
import com.example.qx.zy;
import com.google.android.exoplayer2.ExoPlayer;
import com.google.android.exoplayer2.MediaItem;
import com.google.android.exoplayer2.ui.AspectRatioFrameLayout;
import com.google.android.exoplayer2.ui.PlayerView;
import com.google.android.exoplayer2.util.Log;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Objects;
import java.util.concurrent.CountDownLatch;

public class tianjiaqxqa extends AppCompatActivity {
    private static final  int  a=3;
    private Button buttj,butwc;
    private ImageView imageView;
    private EditText editText;
    private PlayerView playerView;
    private ExoPlayer exoPlayer;
    private data data=new data();
    private String uri=null;
    private  zhangmi zhangmi= com.example.qx.lei.zhangmi.getInstance();
    private cos cos=new cos();

    public tianjiaqxqa() throws SQLException, ClassNotFoundException, IllegalAccessException, InstantiationException {
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tianjiaqxq);

        imageView=findViewById(R.id.fabiaotupian);
        buttj=findViewById(R.id.dakaixc);
        playerView=findViewById(R.id.fabiaoshipin);
        buttj.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectFile();

            }
        });

        butwc=findViewById(R.id.tianjianwc);
      butwc.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v) {
              editText=findViewById(R.id.tianjiaxf);
              String str=editText.getText().toString();

                  ContentResolver contentResolver=getContentResolver();

                  String c=contentResolver.getType(Uri.parse(uri));
                  final int[] i = new int[1];
                    String h=String.valueOf(zhangmi.getZhang());
                  final Connection[] connection = new Connection[1];
                  final leilianxr[] leilianxr = new leilianxr[1];
                  CountDownLatch latch=new CountDownLatch(1);
                  new Thread(new Runnable() {
                      @Override
                      public void run() {
                          try {Class.forName("com.mysql.jdbc.Driver").newInstance();}
                          catch (IllegalAccessException | ClassNotFoundException |
                                 InstantiationException e) {
                              throw new RuntimeException(e);}
                          try {
                              connection[0] = DriverManager.getConnection("jdbc:mysql://sh-cdb-9761pjk2.sql.tencentcdb.com:29081/youqi","root","asd123456");

                              if(data.getallqxq(zhangmi.getZhang(),connection[0]).size()>0){
                                  i[0] =data.getallqxq(zhangmi.getZhang(),connection[0]).get(data.getallqxq(zhangmi.getZhang(),connection[0]).size()-1).getSum();
                                  i[0] = i[0] +1;
                              }
                              else
                                  i[0] =1;
                              data.insertqxq(str,uri,zhangmi.getZhang(), i[0],connection[0]);

                          } catch (SQLException e) {throw new RuntimeException(e);}
                          latch.countDown();
                      }
                  }).start();
                  try{
                      latch.await();
                      connection[0].close();
                  }
                  catch (InterruptedException | SQLException e)
                  {e.printStackTrace();}

              String z=String.valueOf(i[0]);
              if(c.startsWith("image/"))
                  h="a"+h+"qxq"+z;
              else
                  h=h+"qxq"+z;
              cos.insert(Uri.parse(uri),h,getApplication());

              Intent intent=new Intent(tianjiaqxqa.this, qxq.class);
               startActivity(intent);
          }
      });


    }
    public void selectFile(){
       Intent intent =new Intent(Intent.ACTION_OPEN_DOCUMENT);
        intent.setType("*/*");
        intent.addCategory(Intent.CATEGORY_OPENABLE);
       startActivityForResult(intent.createChooser(intent,"选择文件"),a);
    }
    @Override
    protected  void onActivityResult(int request,int result,Intent data){
        super.onActivityResult(request,result,data);
        if(request==a){
            if(result==RESULT_OK){
                Uri selectedFileUri=data.getData();
                 uri=selectedFileUri.toString();
                 ContentResolver contentResolver=getContentResolver();

                   String c=contentResolver.getType(selectedFileUri);

                 try {
                     getApplicationContext().grantUriPermission(getApplication().getPackageName(),selectedFileUri,Intent.FLAG_GRANT_READ_URI_PERMISSION|Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);

                     getContentResolver().takePersistableUriPermission(selectedFileUri,Intent.FLAG_GRANT_READ_URI_PERMISSION|Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                 }catch (SecurityException e){
                     e.printStackTrace();
                 }

                    if(!Objects.equals(c, "s")&&(!c.equals(""))){
                if(c.startsWith("image/")){
                    try {
                        playerView.setVisibility(View.GONE);
                        InputStream inputStream=getContentResolver().openInputStream(selectedFileUri);
                        Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                        imageView.setImageBitmap(bitmap);
                         inputStream.close();
                    }  catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                    final boolean tupian[]={false};
                    imageView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                       if(!tupian[0])
                          {   buttj.setVisibility(View.GONE);
                              butwc.setVisibility(View.GONE);
                              getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN|View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY|View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
                              getSupportActionBar().hide();
                              ConstraintLayout.LayoutParams params2=(ConstraintLayout.LayoutParams) imageView.getLayoutParams();
                              params2.height=ViewGroup.LayoutParams.MATCH_PARENT;
                              params2.width=ViewGroup.LayoutParams.MATCH_PARENT;
                              tupian[0]=true;

                          }
                       else{
                           butwc.setVisibility(View.VISIBLE);
                           buttj.setVisibility(View.VISIBLE);
                           getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
                           getSupportActionBar().show();
                           ConstraintLayout.LayoutParams params3=(ConstraintLayout.LayoutParams) imageView.getLayoutParams();
                           params3.width=(int) (250*getApplicationContext().getResources().getDisplayMetrics().density);
                           params3.height=(int) (150*getApplicationContext().getResources().getDisplayMetrics().density);
                                    tupian[0]=false;
                           }

                                                      }
                    });

                }
                else if (c.startsWith("video/")) {

                    try {
                        imageView.setImageBitmap(null);
                        playerView.setVisibility(View.VISIBLE);
                        exoPlayer=new ExoPlayer.Builder(this).build();
                        playerView.setPlayer(exoPlayer);
                        MediaItem mediaItem= MediaItem.fromUri(selectedFileUri);
                        exoPlayer.setMediaItem(mediaItem);
                        exoPlayer.prepare();
                    }catch (Exception e){
                        Log.e("error","sssss"+e.getMessage());
                    }
                    final boolean[] isfull = {false};
                    final boolean[] kzq = {true};

                    GestureDetector gestureDetector=new GestureDetector(this,new GestureDetector.SimpleOnGestureListener(){
                        @Override
                        public boolean onDoubleTap(MotionEvent e){
                            if(!isfull[0]){
                                buttj.setVisibility(View.GONE);
                                butwc.setVisibility(View.GONE);
                                getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN|View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY|View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
                                getSupportActionBar().hide();
                                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                                ConstraintLayout.LayoutParams params1=(ConstraintLayout.LayoutParams) playerView.getLayoutParams();
                                params1.width=ViewGroup.LayoutParams.MATCH_PARENT;
                                params1.height=ViewGroup.LayoutParams.MATCH_PARENT;
                                playerView.setResizeMode(AspectRatioFrameLayout.RESIZE_MODE_FILL);
                                isfull[0] =true;

                            }
                            else {
                                buttj.setVisibility(View.VISIBLE);
                                butwc.setVisibility(View.VISIBLE);
                                getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
                                getSupportActionBar().show();
                                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                                ConstraintLayout.LayoutParams params=(ConstraintLayout.LayoutParams)playerView.getLayoutParams();
                                params.width=(int) (250*getApplicationContext().getResources().getDisplayMetrics().density);
                                params.height=(int) (150*getApplicationContext().getResources().getDisplayMetrics().density);

                                playerView.setResizeMode(AspectRatioFrameLayout.RESIZE_MODE_FIT);
                                isfull[0]=false;
                            }
                            return true;
                        }
                        @Override
                        public boolean onSingleTapConfirmed(MotionEvent e){
                            if(kzq[0])
                            {playerView.hideController();
                                kzq[0]=false;
                            }
                            else {
                                playerView.showController();
                                kzq[0]=true;
                            }

                            return true;

                        }
                    });
                    playerView.setOnTouchListener(new View.OnTouchListener() {
                        @Override
                        public boolean onTouch(View v, MotionEvent event) {
                            gestureDetector.onTouchEvent(event);
                            return true;
                        }
                    });

                }

                    }


            }
            }
        }
    }

